<template>
  <div class="water-quality-dashboard">
    <div class="panel-header">
      <div class="header-left">
        <div class="card-title">实验室数据统计</div>
        <!-- 手动站统计数据 -->
        <div class="water-quality-stats">
          <div class="stat-item" v-for="(item, index) in overviewData" :key="index">
            <span class="stat-label">{{ item.label }}</span>
            <span class="stat-value">{{ item.value }}{{ item.suffix }}</span>
          </div>
        </div>
      </div>
      <div class="header-right">
        <span class="close-btn" @click="closePanel">×</span>
      </div>
    </div>

    <!-- 水质类别分布环形图 -->
    <div class="card">
      <div class="card-header">
        <div class="card-title">水质类别分布</div>
      </div>
      <div class="chart-container">
        <div ref="waterTypeChart" class="chart water-type-chart"></div>
      </div>
    </div>

    <!-- 主要污染物及占比柱状图 -->
    <div class="card">
      <div class="filter-header">
        <!-- 标题 -->
        <div class="card-title">主要污染物及占比</div>

        <!-- 筛选控件 -->
        <div class="filter-controls">
          <!-- 按月/按年切换 -->
          <el-radio-group v-model="timeGranularity" size="mini" class="time-granularity"
            @change="handleGranularityChange">
            <el-radio-button label="month">按月</el-radio-button>
            <el-radio-button label="year">按年</el-radio-button>
          </el-radio-group>

          <el-date-picker v-if="timeGranularity=='month'" v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" size="mini" :format="timeGranularity === 'month' ? 'yyyy-MM' : 'yyyy'"
            :value-format="timeGranularity === 'month' ? 'yyyy-MM' : 'yyyy'" :picker-options="datePickerOptions"
            @change="handleDateChange" class="date-picker"></el-date-picker>

          <el-date-picker v-if="timeGranularity=='year'" v-model="queryYear" type="year" size="mini" 
            @change="handleDateChange" class="date-picker"></el-date-picker>
        </div>
      </div>

      <div class="zywrw-container">
        <!-- 超标月份/年份前三 -->
        <div class="data-section">
          <div class="zywrw-title">{{ timeGranularity === 'month' ? '超标月份前三' : '超标年份前三' }}</div>
          <ul class="data-list">
            <li class="data-item" v-for="(item, index) in (timeGranularity === 'month' ? cbThreeMonthList : cbThreeYearList)" :key="index">{{ item }}</li>
          </ul>
        </div>

        <!-- 因子累计前三 -->
        <div class="data-section">
          <div class="zywrw-title">因子累计前三</div>
          <ul class="data-list">
            <li class="data-item" v-for="(item, index) in cbThreeItemList" :key="index">{{ item }}</li>
          </ul>
        </div>
      </div>

      <div class="chart-container pollutant-chart-container">
        <div ref="pollutantChart" class="chart pollutant-chart"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { getManualWaterQuality, getMonthPollutantsPropor, getYearPollutantsPropor } from "../../api/shougongduanmian.js";
import * as echarts from 'echarts'

const waterColors = {
  'Ⅰ类': 'rgb(204, 255, 255)', // 优 #ccffff
  'Ⅱ类': 'rgb(0, 204, 255)',   // 良好 #00ccff
  'Ⅲ类': 'rgb(0, 255, 0)',     // 轻度污染 #00ff00
  'Ⅳ类': 'rgb(255, 255, 0)',   // 中度污染 #ffff00
  'Ⅴ类': 'rgb(255, 155, 0)',   // 重度污染 #ff9b00
  '劣Ⅴ类': 'rgb(255, 0, 0)',   // 严重污染 #ff0000
  '无类别': 'rgb(128, 128, 128)',
}


const formatYear = (date) => {
  return date.getFullYear().toString();
};
const formatMonth = (date) => {
  return date.getFullYear() + '-' +
    String(date.getMonth() + 1).padStart(2, '0');
};
// const queryYear=formatYear(new Date())
// 常量配置
const CONSTANTS = {
  // 图表相关样式配置
  CHART_STYLES: {
    TOOLTIP: {
      BACKGROUND: 'rgba(255, 255, 255, 0.9)',
      BORDER_COLOR: '#ddd',
      BORDER_WIDTH: 1,
      TEXT_COLOR: '#333'
    },
    AXIS: {
      LINE_COLOR: '#ccc',
      LABEL_COLOR: '#606266',
      SPLIT_LINE_COLOR: '#f0f0f0'
    },
    LEGEND: {
      TEXT_COLOR: '#606266'
    }
  },
  // 默认日期范围
  DEFAULT_DATE_RANGES: {
    DAY: (function () {
      const today = new Date();
      const oneWeekAgo = new Date(today);
      oneWeekAgo.setDate(today.getDate() - 7);

      const formatDate = (date) => {
        return date.getFullYear() + '-' +
          String(date.getMonth() + 1).padStart(2, '0') + '-' +
          String(date.getDate()).padStart(2, '0');
      };

      return [formatDate(oneWeekAgo), formatDate(today)];
    })(),
    MONTH: (function () {
      const today = new Date();
      const oneYearAgo = new Date(today);
      oneYearAgo.setFullYear(today.getFullYear() - 1);



      return [formatMonth(oneYearAgo), formatMonth(today)];
    }
    )(),
    YEAR: (function () {
      const today = new Date();
      return  formatYear(today);
    })()
  }
}
export default {
  name: 'ShougongduanmianPanel',
  data() {
    return {
      // 时间粒度：month-按月，year-按年
      timeGranularity: 'month',
      // 日期范围
      dateRange: CONSTANTS.DEFAULT_DATE_RANGES.MONTH,
      queryYear: CONSTANTS.DEFAULT_DATE_RANGES.YEAR,
      currentPollutantData: null,
      // 图表实例
      waterTypeChart: null,
      pollutantChart: null,
      // 日期选择器配置
      datePickerOptions: {
        disabledDate(time) {
          // 禁用未来日期
          return time.getTime() > Date.now();
        }
      },
      // 超标月份前三列表
      cbThreeMonthList: [],
      // 超标年份前三列表
      cbThreeYearList: [],
      // 因子累计前三列表
      cbThreeItemList: [],
      overview: {
        allSize: 56,        // 手动站总数
        dataSize: 20,       // 监测断面
        ylsizesize: 19,     // 优良数
        yl: '52.8'          // 优良率
      },
      overviewData: [],
      waterTypeData: [],
      pollutantData: {
        dates: [],
        pollutants: []
      }
    }
  },
  computed: {

  },

  mounted() {
    this.getManualWaterQualityData()
    this.getMonitoringData()
    // 监听窗口大小变化，调整图表尺寸
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 清理事件监听和图表实例，防止内存泄漏
    window.removeEventListener('resize', this.handleResize)
    this.waterTypeChart?.dispose()
    this.pollutantChart?.dispose()
  },
  methods: {
    /**
     * 关闭面板
     */
    closePanel() {
      this.$emit('close');
    },
    
    /**
     * 当前时间粒度下的污染物数据
     */
    setCurrentPollutantData() {
      this.currentPollutantData = this.pollutantData;
    },
    /**
     * 概览数据格式化
     * 将原始数据转换为统计卡片所需的格式
     */
    getManualWaterQualityData() {
      getManualWaterQuality().then(res => {
        let data = res.data.list;
        this.overview = res.data;
        this.isoverList= res.data.isoverList;
        this.overviewData = [
          {
            label: '手动站',
            value: Number(this.overview.allSize),
            valueStyle: { color: '#409EFF', fontSize: '20px', fontWeight: 'bold' },
            suffix: '个',

          },

          {
            label: '监测断面',
            value: Number(this.overview.dataSize),
            valueStyle: { color: '#409EFF', fontSize: '20px', fontWeight: 'bold' },
            suffix:  '个'
          },
          {
            label: '优良数',
            value: Number(this.overview.ylsize),
            valueStyle: { color: '#409EFF', fontSize: '20px', fontWeight: 'bold' },
            suffix: '个',


          },
          {
            label: '优良率',
            value: Number(this.overview.yl),
            valueStyle: { color: '#409EFF', fontSize: '20px', fontWeight: 'bold' },
            suffix: '%'
          }
        ];
        data.forEach(element => {
          this.waterTypeData.push({ value: element.ylsize, name: element.qualityLevelName, itemStyle: { color: waterColors[element.qualityLevelName] }})

        });
        this.initWaterTypeChart()

      })
    },
    getMonitoringData() {
      let apiFunction;
      let startTime;
      let endTime;
      let queryparms ;
      if (this.timeGranularity === 'year') {
        apiFunction = getYearPollutantsPropor;
        //console.log(typeof(this.queryYear))
        if (typeof(this.queryYear)!='string') {
          this.queryYear = formatYear(this.queryYear)
        }
        queryparms = {
          id: this.featureId,
          year: this.queryYear
        }
      } else if (this.timeGranularity === 'month') {
        apiFunction = getMonthPollutantsPropor;
        startTime = this.dateRange[0];
        endTime = this.dateRange[1];
           queryparms = {
          id: this.featureId,
          startTime: startTime,
          endTime: endTime
        }
      } else {
        console.warn('未知的时间段类型:', this.timePeriod);
        return;
      }

      apiFunction(queryparms).then(res => {
        let data = res.data;
        if (this.timeGranularity === 'year') {
          this.cbThreeYearList = data.cbThreeDay.map(item => `${item.DATATIME}(${item.DATACOUNT})`);
          this.pollutantData.dates = data.dayList;    
        } else {
          this.cbThreeMonthList = data.cbThreeMonth.map(item => `${item.DATATIME}(${item.DATACOUNT})`);
          this.pollutantData.dates = data.monthList;
        }
        this.cbThreeItemList = data.cbThreeItem.map(item => `${item.ITEMNAME}(${item.DATACOUNT})`);


        let itemNameList = data.itemNameList;
        let dataList = data.dataList;
        let pollutants = [];
        itemNameList.forEach((item, index) => {
          pollutants.push({ "name": item, "data": dataList[index] })
        });
        this.pollutantData.pollutants = pollutants;
        this.setCurrentPollutantData()
        this.initPollutantChart()
      }).catch(error => {
        console.error('获取监测数据失败:', error);
      });
    },


    /**
     * 初始化图表
     */
    initWaterTypeChart() {
      // 初始化水质类别图表
      if (this.$refs.waterTypeChart) {
        this.waterTypeChart = echarts.init(this.$refs.waterTypeChart)
        this.waterTypeChart.setOption(this.getWaterTypeOption())
      }


    },
    initPollutantChart() {
      // 初始化污染物图表
      if (this.pollutantChart) {
        this.pollutantChart.setOption(this.getPollutantOption())
      }
      else {
        if (this.$refs.pollutantChart) {
          this.pollutantChart = echarts.init(this.$refs.pollutantChart)
          this.pollutantChart.setOption(this.getPollutantOption())
        }
      }

    },



   
getWaterTypeOption() {
  const { TOOLTIP, LEGEND } = CONSTANTS.CHART_STYLES

  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      backgroundColor: TOOLTIP.BACKGROUND,
      borderColor: TOOLTIP.BORDER_COLOR,
      borderWidth: TOOLTIP.BORDER_WIDTH,
      textStyle: { color: TOOLTIP.TEXT_COLOR }
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'center',
      data: this.waterTypeData.map(item => item.name),
         textStyle: {
              color: LEGEND.TEXT_COLOR,
              fontSize: 13,
              rich: {
                bold: {
                  fontWeight: 'bold'
                }
              }
            },
           itemGap: 5,
      // formatter: (name) => {
      //   const item = this.waterTypeData.find(data => data.name === name);
      //   return `${name} ${item ? item.value : 0}个`;
      // }
                formatter: (name) => {
            const item = this.waterTypeData.find(data => data.name === name);
            const total = this.waterTypeData.reduce((sum, data) => sum + (data.value || 0), 0);
            const percentage = total > 0 ? ((item.value / total) * 100).toFixed(2) : '0.00';
            return `${name}  {bold|${item ? item.value : 0}} 个  占比 {bold|${percentage}}%`;
          }
    },
    series: [
      {
        name: '水质类别',
        type: 'pie',
        // center: ['35%', '50%'],
            center: ['30%', '50%'],
            radius: ['70%', '90%'],
        itemStyle: {
          borderRadius: 4,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: { show: false },
        emphasis: {
          label: { show: true, fontSize: 16, fontWeight: 'bold', position: 'center' }
        },
        labelLine: { show: false },
        data: this.waterTypeData
      },
      // 添加一个空的中心圆用于显示达标率
      {
        name: '',
        type: 'pie',
        center: ['30%', '50%'],
        radius: ['0%', '40%'],
        itemStyle: {
          color: 'transparent'
        },
        label: {
          show: true,
          position: 'center',
          formatter: () => {
            return `{title|达标率}\n{value|${this.isoverList.isOver}%}`;
          },
          rich: {
            title: {
              fontSize: 14,
              color: '#666',
              lineHeight: 20
            },
            value: {
              fontSize: 20,
              fontWeight: 'bold',
              color: '#409EFF',
              lineHeight: 30
            }
          }
        },
        data: [100]
      }
    ]
  }
},
    /**
     * 获取污染物图表配置
     */
    getPollutantOption() {

      const { TOOLTIP, AXIS } = CONSTANTS.CHART_STYLES
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          backgroundColor: TOOLTIP.BACKGROUND,
          borderColor: TOOLTIP.BORDER_COLOR,
          borderWidth: TOOLTIP.BORDER_WIDTH
        },
        // legend: {
        //   data: this.currentPollutantData.pollutants.map(item => item.name),
        //   top: 0,
        //   left: 'center',
        //   width: '100%',
        //   textAlign: 'center'
        // },
            legend: {
          data: this.currentPollutantData.pollutants.map(item => item.name),
          // top: 0,
          // left: 'center',
          // width: '100%',
          // textAlign: 'center',
          type: 'scroll',
          top: 0,
          left: 'center',
          right: 'center',
          width: '90%',
          textAlign: 'center',
          itemWidth: 15,
          itemHeight: 10,
          textStyle: { fontSize: 12 }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
          top: 60
        },
        xAxis: {
          type: 'category',
          data: this.currentPollutantData.dates,
          axisLine: { lineStyle: { color: AXIS.LINE_COLOR } },
          axisLabel: { color: AXIS.LABEL_COLOR }
        },
        yAxis: {
          type: 'value',
          axisLine: { lineStyle: { color: AXIS.LINE_COLOR } },
          axisLabel: { color: AXIS.LABEL_COLOR },
          splitLine: { lineStyle: { color: AXIS.SPLIT_LINE_COLOR } }
        },
             series: this.currentPollutantData.pollutants.map(pollutant => ({
          name: pollutant.name,
          type: 'bar',
          stack: '总量', // 添加堆叠配置
          data: pollutant.data,
          itemStyle: { color: pollutant.color },
          emphasis: {
            itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0, 0, 0, 0.3)' }
          },
          barCategoryGap: '30%'
        }))
        // series: this.currentPollutantData.pollutants.map(pollutant => ({
        //   name: pollutant.name,
        //   type: 'bar',
        //   data: pollutant.data,
        //   itemStyle: { color: pollutant.color },
        //   emphasis: {
        //     itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0, 0, 0, 0.3)' }
        //   },
        //   barCategoryGap: '30%'
        // }))
      }
    },

    /**
     * 处理窗口大小变化，调整图表尺寸
     */
    handleResize() {
      this.waterTypeChart?.resize()
      this.pollutantChart?.resize()
    },

    /**
     * 处理时间粒度变化
     */
    handleGranularityChange(granularity) {
      this.timeGranularity = granularity
    this.getMonitoringData()
    },

    /**
     * 处理日期范围变化
     */
    handleDateChange(range) {
    this.getMonitoringData()
    }
  }
}

</script>

<style lang="scss" scoped>
/* SCSS变量定义 */
$bg-color: #fff;
$card-bg: #fff;
$border-color: #ebeef5;
$border-light: #f0f0f0;
$text-primary: #333;
$primary-color: #409EFF;

/* 主容器样式 */
.water-quality-dashboard {
  background-color: $bg-color;
  height: calc(100vh - 150px);

  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    background: #307EFF;
    // border-bottom: 1px solid #e8e8e8;
    height: 80px;
    border-radius: 0;

    .header-left {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      flex: 1;
      
      .card-title {
        margin: 5px 0px 0px 10px;
        font-family: Source Han Sans CN;
        font-weight: 500;
        font-size: 18px;
        color: #FFFFFF;
      }
      
      /* 水质统计数据样式 */
      .water-quality-stats {
        margin: 10px 0px 0px 10px;
        display: flex;
        flex-wrap: nowrap;
        gap: 10px;
        // margin-top: 20px;
        overflow-x: auto;
        padding-bottom: 5px;
      }
      
      .stat-item {
        display: flex;
        flex-direction: row;
        align-items: center;
        padding: 3px 0px;
        background: rgba(255, 255, 255, 0.1);
        min-width: 50px;
        flex-shrink: 0;
        border-radius: 0;
      }
      
      .stat-label {
        font-size: 11px;
        color: rgba(255, 255, 255, 0.9);
        margin-right: 6px;
      }
      
      .stat-value {
        font-size: 14px;
        font-weight: bold;
        color: #fff;
      }
    }

    .header-right {
      .close-btn {
        font-size: 24px;
        color: #fff;
        cursor: pointer;
        transition: color 0.3s;
        margin-right: 10px;

        &:hover {
          color: rgba(255, 255, 255, 0.8);
        }
      }
    }
  }
}

/* 卡片样式 */
.card {
  background-color: $card-bg;
  transition: all 0.3s ease;
  margin-bottom: 5px;
  margin-top: 5px;
}

.card-header {
  display: flex;
  align-items: center;
  padding-bottom: 12px;

  .card-title {
    margin: 10px 0px 0px 10px;
    font-size: 18px;
    font-weight: bold;
    color: $text-primary;
  }
}

/* 筛选头部样式 */
.filter-header {
  margin-top: 5px;
  // border-bottom: 1px solid $border-light;
  margin-bottom: 5px;
  
  .card-title {
    margin: 10px 0px 0px 10px;
    font-size: 18px;
    font-weight: bold;
    color: $text-primary;
  }
  
  /* 筛选控件相关样式 */
  .filter-controls {
    display: flex;
    align-items: center;
    gap: 15px;
     margin: 10px 10px 0px 10px;
    
    .time-granularity {
      display: inline-flex;
    }
  }
}

/* 主要污染物数据展示样式 */
.zywrw-container {
  display: flex;
  justify-content: space-between;
  // margin-bottom: 15px;
}

.data-section {
  flex: 1;
  margin-right: 20px;
  padding: 10px;
  background-color: rgba(240, 242, 245, 0.5);

  &:last-child {
    margin-right: 0;
  }
}

.zywrw-title {
  display: block;
  margin-bottom: 5px;
  white-space: nowrap;
  font-weight: bold;
  text-align: center;
}

.data-list {
  margin: 0;
  padding-left: 10px;
}

.data-item {
  display: block;
  // margin-bottom: 8px;
  padding: 2px 4px;
  font-weight: bold;
  color: $primary-color;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: center;
  
  &:last-child {
    margin-bottom: 0;
  }
}

/* 图表相关样式 */
.chart-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.chart {
  width: 100%;
  
  &.water-type-chart {
    height: 180px;
  }
  
  &.pollutant-chart {
    height: 220px;
  }
}
</style>
